﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MiniHttpd;
using System.IO;

namespace CalcDataServ
{
    class Program
    {
        internal static ConfigReader Config;
        internal static Data Db;
        internal static Dictionary<string, string> MimeTypes;
        internal static string AppDir;

        static void Main(string[] args)
        {
            Db = new Data("Data.sdf");
            if (!Db.DatabaseExists()) Db.CreateDatabase();
            CreateMimeDb();
            string[] cmd = Environment.CommandLine.Split(' ');
            cmd[0] = cmd[0].Remove(cmd[0].Length - 1);
            cmd[0] = cmd[0].Remove(0, 1);
            AppDir = Path.GetDirectoryName(cmd[0]);

            try
            {
                Config = new ConfigReader();
                Config["ServerRoot"] = ((string)Config["ServerRoot"]).Replace("%Appdir%", AppDir);;
                Server srv = new Server();
                srv.RunServer();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
        }

        static void CreateMimeDb()
        {
            MimeTypes = new Dictionary<string, string>();
            if (File.Exists("mime.txt"))
            {
                TextReader txt = File.OpenText("mime.txt");
                string content = txt.ReadToEnd().Replace("\r\n", "\n");
                txt.Close();
                string[] lines = content.Split('\n');
                content = null;
                string[] tmp;
                foreach (string line in lines)
                {
                    if (line.Length > 0)
                    {
                        if (!line.StartsWith("//"))
                        {
                            tmp = line.Split(';');
                            if (tmp.Length != 2) continue;
                            if (MimeTypes.ContainsKey(tmp[0])) MimeTypes[tmp[0]] = tmp[1];
                            else MimeTypes.Add(tmp[0], tmp[1]);
                        }
                    }
                }
            }
        }
    }
}
